<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- BIM获奖台账 -->
    <div id="base-breadcrumb" style="position: relative; overflow: hidden">
      <!-- 搜索 -->
      <searchData
        :search-data="searchArr"
        @search="search"
        @onSelectChange="
          (e) => {
            unitCode = e.code
          }
        "
      />
      <!-- 表格 -->
      <a-card :bordered="false">
        <!-- <title-name :title="$route.meta.title" /> -->
        <!-- 表格 -->
        <list-table
          ref="table"
          :page-keys="['pageNum', 'pageSize', 'total']"
          :columns="columns"
          :request="loadData"
          :start-index="0"
          :filter-data="filterData"
          :statistics-config="{
            use: true, //是否统计，传false不会显示操作栏
            temp: statistics
          }"
          :export-permission="{ select: 'BIM_003_exp_05', all: 'BIM_003_exp_05' }"
          :export-config="{ use: true, select: $route.meta.title, all: $route.meta.title }"
        >
          <!-- 新增 -->
          <a-button
            slot="prefix"
            v-btnPermission="'BIM_003_add_01'"
            class="mb12"
            icon="plus"
            type="primary"
            @click="handleManage(2)"
          >
            新增
          </a-button>
          <!-- 下载附件 -->
          <template slot="suffix" slot-scope="scoped">
            <a-button
              v-btnPermission="'BIM_003_dow_06'"
              :loading="downLoading"
              class="mb12"
              icon="cloud-download"
              :disabled="scoped.selectedRowKeys && scoped.selectedRowKeys.length === 0"
              type="primary"
              @click="downZip(scoped.selectedRowsMap)"
            >
              批量下载附件
            </a-button>
            <ExportExcel
              ref="exportExcel"
              :export-list="exportList"
              :loading="loadingExport"
              icon="export"
              :file-name="$route.meta.title + '模板.xlsx'"
              button-text="下载导入模板"
              :beforeDownload="beforeDownload"
            />
            <ExcelImportButton
              ref="excelImportButton"
              :loading="loadingImport"
              icon="import"
              button-text="批量导入"
              @handleSubmit="handleImport"
            />
          </template>
          <template slot="actions" slot-scope="text, record">
            <MoreButton>
              <template v-if="record.fileInfoList && record.fileInfoList.length > 0">
                <a
                  v-btnPermission="'BIM_003_loo_02'"
                  @click="
                    fileList = record.fileInfoList
                    visible = true
                  "
                  >查看附件({{ record.fileInfoList ? record.fileInfoList.length : 0 }})</a
                >
                <!-- <a
                v-btnPermission="'BIM_003_loo_02'"
                @click="handleManage(0, record)"
              >查看</a> -->
              </template>
              <a v-btnPermission="'BIM_003_edi_03'" @click="handleManage(1, record)">编辑</a>
              <template>
                <a v-btnPermission="'BIM_003_del_04'" class="del_btn" @click="handleRemove(record.id, search)">删除</a>
              </template>
            </MoreButton>
          </template>
        </list-table>
      </a-card>
    </div>
    <!-- 查看附件 -->
    <DialogForm ref="dialogForm" :visible.sync="visible" edit-model="V" :width="1000" :fileList="fileList" />
    <ExportResult :visible.sync="visibleExport" :exportList="exportList" width="80%" />
  </base-breadcrumb>
</template>

<script>
import { getPageTypesLabel, getTreeLabelByBimAward } from '@/api/bimIntegrate/bimResource.js'
import {
  getPageBimAwardLedger,
  deleteBimAwardLedger,
  listTotal,
  insertBimAwardLedgerBatch
} from '@/api/bimIntegrate/bimResult.js'
import BasePage from '@/views/basePage'
import Selector from '@/components/Select/Selector'
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
import SelectProject from '@/components/Select/SelectProject'
import DialogForm from '@/components/DialogForm' // 弹窗
import ExportExcel from '@/components/exportExcel/ExportExcel' // 导出
import ExportResult from '@/components/Dialog/ExportResult' // 弹窗

const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    fixed: 'left',
    isHidden: true,
    width: 80,
    customRender() {
      return Number(arguments[2]) + 1
    }
  },
  {
    title: '单位',
    ellipsis: true,
    dataIndex: 'unitName'
  },
  {
    title: '获奖时间',
    ellipsis: true,
    dataIndex: 'awardTime',
    excelConfig: {
      note: '日期格式：XXXX年XX月XX日；如：2020年5月1号'
    }
  },
  {
    title: '申报项目',
    ellipsis: true,
    dataIndex: 'projectName'
  },
  {
    title: '申报时间',
    ellipsis: true,
    dataIndex: 'declareTime',
    excelConfig: {
      note: '日期格式：XXXX年XX月XX日；如：2020年5月1号'
    }
  },
  {
    title: '比赛名称',
    ellipsis: true,
    dataIndex: 'gameName',
    excelConfig: {
      dataValidation: {
        type: 'list'
      }
    }
  },
  {
    title: '举办单位',
    ellipsis: true,
    dataIndex: 'organizers',
    excelConfig: {
      dataValidation: {
        type: 'list'
      }
    }
  },
  {
    title: '奖项级别',
    ellipsis: true,
    dataIndex: 'awardLevelName',
    excelConfig: {
      dataValidation: {
        type: 'list'
      }
    }
  },
  {
    title: '奖项名称',
    ellipsis: true,
    dataIndex: 'awardName',
    excelConfig: {
      dataValidation: {
        type: 'list'
      }
    }
  },
  {
    title: '主要完成人',
    ellipsis: true,
    dataIndex: 'completeUserName',
    excelConfig: {
      note: '多条采用小写逗号分隔，如：张三,李四'
    }
  },
  {
    title: '证书原件保管单位',
    dataIndex: 'certificateAddress'
  },
  {
    title: '更新时间',
    isHidden: true,
    width: 160,
    ellipsis: true,
    dataIndex: 'modifiedTime'
  },
  {
    title: '操作',
    isHidden: true,
    dataIndex: 'actions',
    width: '230px',
    align: 'center',
    fixed: 'right',
    scopedSlots: { customRender: 'actions' }
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BasePage(),
  components: {
    DialogForm,
    ExportResult,
    ExportExcel
  },
  data() {
    this.columns = columns
    return {
      queryParam: {}, // 查询参数
      unitCode: '', // 所选单位层级
      visible: false, // 查看附件弹窗控件
      visibleExport: false, // 导入结果弹窗控件
      exportList: [{ columns: [], datas: [] }], // 导入配置项
      fileList: [], // 当前文件列表
      loadingImport: false, // 导入loading
      loadingExport: false, // 导出loading
      removeApi: { remove: deleteBimAwardLedger }, // 删除台账
      countInfo: {}, // 汇总数据
      countList: [
        {
          title: '世界级：',
          value: 'world'
        },
        {
          title: '国家级：',
          value: 'country'
        },
        {
          title: '省市级：',
          value: 'province'
        },
        {
          title: '局级：',
          value: 'bureau'
        },
        {
          title: '公司级：',
          value: 'company'
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        this.getSummary()
        const requestParameters = Object.assign({}, parameter, { param: this.queryParam })
        return getPageBimAwardLedger(requestParameters).then((res) => {
          if (res.code === '0') {
            return { code: 200, data: res.data?.list, total: res.data?.total }
          }
        })
      },
      importCheck: {
        单位: 'unitName',
        获奖时间: 'awardTime',
        申报项目: 'projectName',
        申报时间: 'declareTime',
        比赛名称: 'gameName',
        举办单位: 'organizers',
        奖项级别: 'awardLevelName',
        奖项名称: 'awardName',
        主要完成人: 'completeUserName',
        证书原件保管单位: 'certificateAddress'
      } // 导入字段对应
    }
  },
  computed: {
    // 搜索配置项
    searchArr() {
      return [
        // 搜索框
        {
          name: '单位',
          valueKey: 'unitId',
          type: SelectCompanyAndProject,
          extraParams: {
            notContainTags: ['PD']
          }
        },
        {
          name: '申报项目',
          type: SelectProject,
          valueKey: 'projectId',
          keyValue: 'unitId',
          unitCode: this.unitCode
        },
        {
          name: '比赛名称',
          valueKey: 'gameNameId',
          type: Selector,
          customApi: getTreeLabelByBimAward,
          dataValue: 'data.awardNameList'
        },
        {
          name: '申报时间',
          type: 'dateRange',
          value: 'trainTime',
          attr: {
            rangeFormat: ['startTime', 'endTime']
          }
        },
        {
          name: '获奖时间',
          type: 'dateRange',
          value: 'awardTime',
          attr: {
            rangeFormat: ['awardStartTime', 'awardEndTime']
          }
        },
        {
          name: '奖项级别',
          valueKey: 'awardLevelName',
          type: Selector,
          valueName: 'name',
          customApi: getTreeLabelByBimAward,
          dataValue: 'data.awardLevelList'
        },
        {
          name: '举办单位',
          valueKey: 'organizersId',
          type: Selector,
          customApi: getTreeLabelByBimAward,
          dataValue: 'data.organizersList'
        },
        {
          name: '奖项名称',
          valueKey: 'awardNameId',
          type: Selector,
          customApi: getPageTypesLabel,
          customQuery: { param: { type: '30' } },
          dataValue: 'data.list'
        }
      ]
    }
  },
  methods: {
    /**
     * @description: 导出模板前的回调处理
     * @param {Promise} callback：导出方法
     */
    async beforeDownload() {
      let columnsExport = this.$clone(this.columns)
      // 若比赛名称等枚举值不存在，则添加比赛名称等的枚举值
      if (
        !columnsExport[5].options ||
        columnsExport[5].options.length === 0 ||
        !columnsExport[6].options ||
        columnsExport[6].options.length === 0 ||
        !columnsExport[7].options ||
        columnsExport[7].options.length === 0
      ) {
        this.loadingExport = true
        const res = await getTreeLabelByBimAward().catch(() => {
          this.loadingExport = false
        })
        if (res.code === '0') {
          // 添加比赛名称枚举
          columnsExport[5].options = res.data?.awardNameList?.map((item) => item.name)
          // 添加举办单位枚举
          columnsExport[6].options = res.data?.organizersList?.map((item) => item.name)
          // 添加奖项级别枚举
          columnsExport[7].options = res.data?.awardLevelList?.map((item) => item.name)
        }
      }
      // 若奖项名称枚举值不存在，则添加奖项名称的枚举值
      if (!columnsExport[8].options || columnsExport[8].options.length === 0) {
        const res = await getPageTypesLabel({ param: { type: '30' } }).catch(() => {
          this.loadingExport = false
        })
        this.loadingExport = false
        if (res.code === '0') {
          // 添加奖项名称枚举
          columnsExport[8].options = res.data?.list?.map((item) => item.name)
        }
      } else {
        this.loadingExport = false
      }
      // 设置默认导出配置项
      this.exportList = [
        {
          columns: columnsExport,
          datas: [
            {
              completeUserName: '完成该成果的人员（可添加多人）',
              unitName: '完成该成果的项目部'
            }
          ]
        }
      ]
    },
    /**
     * @description: 批量导入
     * @param {Array} data：导入列表
     */
    async handleImport(e) {
      let form = []

      // 遍历校验表格字段，且添加表单
      for (let index in e) {
        form.push({})
        let keys = e[index]
        let listItem = form[index]
        // 校验excel的表头字段
        for (let i in this.importCheck) {
          let item = this.importCheck[i]
          if (!Object.keys(keys).includes(i) && item !== 'remark') {
            this.$message.warning(`第${Number(index) + 1}行${i}不能为空`)
            return
          } else {
            // 添加表单值，且格式化日期
            try {
              listItem[item] =
                item === 'declareTime' || item === 'awardTime'
                  ? this.$dateFormat(keys[i].setDate(keys[i].getDate() - 1), 'D')
                  : keys[i]
            } catch (error) {
              console.log(error)
              this.$message.warning(`第${Number(index) + 1}行${i}格式有误`)
              return
            }
          }
        }
      }
      // 开始导入
      this.loadingImport = true
      const importRes = await insertBimAwardLedgerBatch(form).catch(() => {
        this.loadingImport = false
      })
      // 导入成功
      if (importRes.code === '0') {
        if (importRes.data?.list?.length > 0) {
          // 配置导出项，且打开导出结果
          let columnsExport = this.$clone(this.columns)?.filter((i) => i.header !== '操作' && !i.isHidden)
          if (
            !columnsExport[4].options ||
            columnsExport[4].options.length === 0 ||
            !columnsExport[5].options ||
            columnsExport[5].options.length === 0 ||
            !columnsExport[6].options ||
            columnsExport[6].options.length === 0
          ) {
            const ress = await getPageTypesLabel({ param: { type: '31' } }).catch(() => {
              this.loadingImport = false
            })
            // 添加下拉枚举值
            if (ress.code === '0') {
              // 添加比赛名称枚举
              columnsExport[4].options = ress.data?.awardNameList?.map((item) => item.name)
              // 添加举办单位枚举
              columnsExport[5].options = ress.data?.organizersList?.map((item) => item.name)
              // 添加奖项级别枚举
              columnsExport[6].options = ress.data?.awardLevelList?.map((item) => item.name)
            }
          }
          // 若奖项名称枚举值不存在，则添加奖项名称的枚举值
          if (!columnsExport[7].options || columnsExport[7].options.length === 0) {
            const res = await getPageTypesLabel({ param: { type: '30' } }).catch(() => {
              this.loadingImport = false
            })
            this.loadingImport = false
            if (res.code === '0') {
              // 添加奖项名称枚举
              columnsExport[7].options = res.data?.list?.map((item) => item.name)
            }
          } else {
            this.loadingImport = false
          }
          // 表头添加失败原因
          columnsExport.push({
            dataIndex: 'failureReason',
            ellipsis: true,
            title: '失败原因'
          })

          this.exportList = [
            {
              successCount: importRes.data.successCount,
              columns: columnsExport,
              datas: importRes.data.list
            }
          ]
          this.visibleExport = true
        } else {
          this.loadingImport = false
          this.$message.success('导入成功')
        }
        // 如果有导入成功条数，则刷新表格
        importRes.data?.successCount > 0 && this.search()
      }
    },
    /**
     * 格式话数据
     */
    filterData(datas) {
      let list = this.$clone(datas)
      list.forEach((item, index) => {
        item.index = index + 1
      })
      return list
    },
    /**
     * 汇总请求
     */
    getSummary() {
      listTotal({ param: this.queryParam }).then((res) => {
        if (res.code === '0') {
          this.countInfo = res.data
        }
      })
    },
    /**
     * 汇总
     */
    statistics() {
      return this.countList.map((item, index) => (
        <span key={index}>
          {item.title}
          <a>
            <b>{this.countInfo?.[item.value] || 0}</b>
          </a>
          个{index != this.countList.length - 1 ? '，' : ''}
        </span>
      ))
    },
    /**
     * 搜索
     */
    search(value) {
      value && (this.queryParam = value)
      this.$refs.table.getData(null, true)
    },
    /**
     * 操作栏
     */
    handleManage(type, record) {
      this.editModel = type
      let query = {
        editModel: type
      }
      if (record && record.id) {
        query.id = record.id
      }
      this.$router.push({
        name: '/bimResult/ledgerEdit',
        query
      })
    }
  }
}
</script>
